using System;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;

namespace OpenWaves.ActivityFeed.RavenDB
{
    public class DocumentStoreFactoryConfiguration : IDocumentStoreFactoryConfiguration
    {
        [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
        public DocumentStoreCreationMethod CreationMethod
        {
            get
            {
                var connectionSettings = ConfigurationManager.ConnectionStrings["ActivityFeed"];

#if NET_40_OR_GREATER
                if (connectionSettings == null || connectionSettings.ConnectionString.Equals("Memory", StringComparison.OrdinalIgnoreCase))
                    return DocumentStoreCreationMethod.InMemory;
#endif
                Url connectionString;
                if (OpenWaves.Url.TryParse(connectionSettings.ConnectionString, out connectionString) == false)
                    return DocumentStoreCreationMethod.Remote;

#if NET_40_OR_GREATER
                if (connectionString is FileUrl)
                    return DocumentStoreCreationMethod.Embedded;
                else
                    return DocumentStoreCreationMethod.Remote;
#else
                return DocumentStoreCreationMethod.Remote;
#endif
            }
        }

        public string ConnectionString
        {
            get
            {
                var connectionSettings = ConfigurationManager.ConnectionStrings["ActivityFeed"];
                Contract.Assert(connectionSettings != null);

                Url url;
                if (OpenWaves.Url.TryParse(connectionSettings.ConnectionString, out url) && url is AbsoluteUrl)
                    return "Url=" + connectionSettings.ConnectionString;

                return connectionSettings.ConnectionString;
            }
        }

        public string DataDirectory
        {
            get
            {
                var connectionSettings = ConfigurationManager.ConnectionStrings["ActivityFeed"];
                Contract.Assert(connectionSettings != null);

                var url = OpenWaves.Url.Parse(connectionSettings.ConnectionString);
                var fileUrl = url as FileUrl;
                Contract.Assert(fileUrl != null, "ActivityFeed connection string must be a valid FileUrl when using Embedded Document Store.");

                return fileUrl.Path.ToString();
            }
        }
    }
}